import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { querymenus } from "../request/api";
import { useMainStore } from "../store";
import { getrouter, treeFindPath, treeFind } from "../common/common"
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";


const history = createWebHistory()
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/login",
  },
  //登录页面
  {
    path: "/login",
    name: "Login",
    component: () => import("../components/Login.vue"),
  },
  //404页面
  {
    path: "/404",
    name: "404",
    component: () => import("../components/404.vue"),
  },
  //主页
  {
    path: "/home",
    name: "Home",
    component: () => import("../components/Home.vue"),
  },
];
const router = createRouter({
  history,
  routes,
  //禁用后退前进按钮
  scrollBehavior: () => {
    window.history.pushState(history.state, null, document.URL)
  }

})





//挂载路由导航守卫
router.beforeEach(async (to, from, next) => {
  //to 将要访问的路径
  //from 代表从哪个路径跳转而来
  //next 是一个函数,表示方形
  //   next() 放行  next('/login') 强制跳转


  if (to.path == '/login' || to.path == '/404') return next();

  //获取token
  const tokenStr = window.sessionStorage.getItem('token')

  //获取菜单栏
  // const menus = JSON.parse(window.sessionStorage.getItem('menus'))



  if (!tokenStr) {
    return next('/login')
    //表示执行了刷新操作或者是第一次进入主页
  } else if (router.getRoutes().length <= 4) {
    const { data: res } = await querymenus();
    if(res.code==200){
      const menus = res.data
      //把动态菜单的数据添加到store里
      const mainStore = useMainStore();
      mainStore.menus = menus
      //添加动态路由
      var menusroutes = []
      getrouter(menus, menusroutes)
  
      var i = 1
      menusroutes.forEach(element => {
  
        if (i == 1) {
          router.addRoute({
            path: "/home",
            name: "Home",
            redirect: element.path,
            component: () => import("../components/Home.vue"),
          });
          //添加头部的tabs
          mainStore.headertabs.push({
            title: element.title,
            name: element.path.replace("/", ""),
            close: false
          })
          mainStore.activetab = element.path.replace("/", "")
          i--
        }
        router.addRoute('Home', {
          path: element.path,
          name: element.name,
          component: () => import('../components/' + element.component)
        });
  
      });
      // console.log(menusroutes)
      // console.log(router.getRoutes())
      next({ ...to, replace: true })

    }else{
      ElMessage.error(res.msg)
      return next('/login')
      
    }
  
    //找不到路由，跳转到404页面
  } else if (!router.hasRoute(to.path.replace("/", ""))) { return next('/404') }
  else {


    const mainStore = useMainStore();
    mainStore.activrouter = to.path.replace("/", "")
    const { menus, headertabs, cacheroute } = storeToRefs(mainStore);
    // console.log(res1.value)
    var activemenus = []
    treeFindPath(menus.value, activemenus, mainStore.activrouter)
    var breadcrumb = []//面包屑

    activemenus.forEach(element => {
      breadcrumb.push(element.menu_name)

    });

    mainStore.$patch({
      activrmenus: activemenus,
      activeName: activemenus[0].menu_name,
      toptitle: activemenus[0].menu_name,
      leftmenus: activemenus[0].child,
      activerindex: mainStore.activrouter,
      breadcrumb: breadcrumb

    })

    //左侧菜单默认激活
    mainStore.activerindex = mainStore.activrouter




    //home头部tabs赋值
    const acitvemenu = treeFind(menus.value, mainStore.activrouter)
    var tabtitle = headertabs.value.find(e => e.title == acitvemenu.menu_name)
    if (!tabtitle) {
      mainStore.headertabs.push({
        title: acitvemenu.menu_name,
        name: acitvemenu.menu_path,
        close: "closable"
      })

    }
    //头部tab的默认激活
    mainStore.activetab = acitvemenu.menu_path

    //如果当前路由没有被添加过，那么添加路由缓存
    if (!mainStore.cacheroute.includes(mainStore.activrouter)) {
      mainStore.cacheroute.push(mainStore.activrouter)
    }









    next()
  }


})
export default router